import axios from 'axios';
import {ElMessage} from "element-plus";

const TOKEN = "token";

// 注意：Vite 使用 import.meta.env 而不是 process.env
axios.defaults.baseURL = import.meta.env.VITE_BASE_URL;

export async function getJson(url, params) {
    return await baseReq(url, "GET", params);
}

export async function postJson(url, data) {
    return await baseReq(url, "POST", null, data);
}

export async function putJson(url, data) {
    return await baseReq(url, "PUT", null, data);
}

export async function deleteJson(url, data) {
    return await baseReq(url, "DELETE", null, data);
}

export async function postForm(url, data) {
    return await baseReq(url, "POST", null, data, {
        'Content-Type': 'multipart/form-data'
    });
}

export async function baseReq(url, method, params, data = {}, headers = {}) {
    const res = await axios({
        method,
        url,
        params,
        data,
        headers,
        timeout: 10000
    });
    return res.data;
}

// 请求拦截器
axios.interceptors.request.use(config => {
    const token = localStorage.getItem(TOKEN);
    if (token) {
        config.headers[TOKEN] = token;
    }
    return config;
}, error => {
    return Promise.reject(error);
});

// 响应拦截器
axios.interceptors.response.use(response => {
    if (response.status === 200 && response.data != null) {
        if (response.data.code === 1) {
            return Promise.resolve(response);
        }
        if (response.data.code === 2) {
            // 错误消息处理将在插件安装时设置
            return Promise.resolve(response);
        }
        if (response.data.code === 8) {
            // 登录过期处理将在插件安装时设置
            return Promise.reject(response);
        }
        return Promise.resolve(response);
    }
    return Promise.reject(response);
}, error => {
    return Promise.reject(error);
});
